$.extend($.fn.datagrid.methods, {
	editCell: function(jq,param){
		return jq.each(function(){
			var opts = $(this).datagrid('options');
			var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
			for(var i=0; i<fields.length; i++){
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor1 = col.editor;
				if (fields[i] != param.field){
					col.editor = null;
				}
			}
			$(this).datagrid('beginEdit', param.index);
			for(var i=0; i<fields.length; i++){
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor = col.editor1;
			}
		});
	}
});
var editIndex = undefined;
function endEditing(){
	if (editIndex == undefined){return true}
	if ($('#usrManager').datagrid('validateRow', editIndex)){
		$('#usrManager').datagrid('endEdit', editIndex);
		editIndex = undefined;
		return true;
	} else {
		return false;
	}
}
function onClickCell(index, field){
	if (endEditing()){
		$('#usrManager').datagrid('selectRow', index)
				.datagrid('editCell', {index:index,field:field});
		editIndex = index;
	}
}
function onClickRow(index){
	if (editIndex != index){
		if (endEditing()){
			$('#usrManager').datagrid('selectRow', index)
					.datagrid('beginEdit', index);
			editIndex = index;
		} else {
			$('#usrManager').datagrid('selectRow', editIndex);
		}
	}
}
function removeit(){
	var rows = $('#usrManager').datagrid('getChecked');
	if(rows){
		var data=JSON.stringify(rows)
		var success=function(){
			$.messager.alert("提示", "提交成功！");
			$.each(rows,function(n,value){
				var idx=$('#usrManager').datagrid('getRowIndex',value);
				$('#usrManager').datagrid('cancelEdit', idx)
				        .datagrid('deleteRow', idx);
			});
		}
		var err=function(error){
			$.messager.alert("提示", error);
		};
		control('delete', data,success,err);
		
	}
	
	
}
function accept(){
	if (endEditing()){
		var datas,crl='save';
		var inserted = $('#usrManager').datagrid('getChanges', "inserted");
		if(inserted.length)datas=inserted;
		else{
			datas=$('#usrManager').datagrid('getChanges');
			crl='update';
		}
		for(var i=0;i<datas.length;i++){
			var dt=datas[i];
			if(dt.check!=undefined)delete dt.check;
		}
		var data=JSON.stringify(datas);
		var success=function(){
			$.messager.alert("提示", "提交成功！");
			$('#usrManager').datagrid('acceptChanges');
		}
		var err=function(error){
			$.messager.alert("提示", error);
		};
		control(crl,data,success,err);
		
	}
}
function reject(){
	$('#usrManager').datagrid('rejectChanges');
	editIndex = undefined;
}
function getChanges(){
	var rows = $('#usrManager').datagrid('getChanges');
	alert(rows.length+' rows are changed!');
}
function append(){
	if (endEditing()){
		$('#usrManager').datagrid('appendRow',{check:'1',id:uuid(),srcode:'',srcname:'',srcuri:'',remark:''});
		editIndex = $('#usrManager').datagrid('getRows').length-1;
		$('#usrManager').datagrid('selectRow', editIndex);
	}
}
function uuid() {
	var s = [];
	var hexDigits = "0123456789abcdefjhigklmnopqrstuvwxyz";
	for (var i = 0; i < 36; i++) {
	s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4";
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); 
	s[8] = s[13] = s[18] = s[23] = "-";
	var uuid = s.join("");
	uuid=uuid.replace(/-/g,"");
	uuid=uuid.toUpperCase();
	return uuid;
}
function control(url, data,success,err){
	$.ajax({ url: url,
	     type:"post",
	     contentType : 'application/json', 
	     data:data,
	     success: function(){
	    	 if(success)success();
         },
         error : function(error){
        	 if(err)err(error);
         }
     });
}
function pagerFilter(data){
	if (typeof data.length == 'number' && typeof data.splice == 'function'){	// is array
		data = {
			total: data.length,
			rows: data
		}
	}
	var dg = $(this);
	var opts = dg.datagrid('options');
	var pager = dg.datagrid('getPager');
	pager.pagination({
		beforePageText:'第',
		afterPageText:'页, 共{pages}页',
		displayMsg:'当前显示从第{from}条到{to}条 共{total}条记录',
		onSelectPage:function(pageNum, pageSize){
			opts.pageNumber = pageNum;
			opts.pageSize = pageSize;
			pager.pagination('refresh',{
				pageNumber:pageNum,
				pageSize:pageSize
			});
			dg.datagrid('loadData',data);
		}
	});
	if (!data.originalRows){
		data.originalRows = (data.rows);
	}
	var start = (opts.pageNumber-1)*parseInt(opts.pageSize);
	var end = start + parseInt(opts.pageSize);
	data.rows = (data.originalRows.slice(start, end));
	return data;
}
function formatPrice(val){
	if (val < 1){
		return '<span style="color:red;">停用</span>';
	} else {
		return '<span style="color:blue;">启用</span>';
	}
}
$(function(){
    $('#createdate').datebox({
    	formatter:function(date){
    		var y = date.getFullYear();
    		var m = date.getMonth()+1;
    		var d = date.getDate();
    		return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
    	},
    	parser:function(s){
    		if (!s) return new Date();
    		var ss = (s.split('-'));
    		var y = parseInt(ss[0],10);
    		var m = parseInt(ss[1],10);
    		var d = parseInt(ss[2],10);
    		if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
    			return new Date(y,m-1,d);
    		} else {
    			return new Date();
    		}
    	}
    });
	$('#usrManager').datagrid({loadFilter:pagerFilter});
	$('#doQuery').click(function(){
		$('#queryForm').form('submit',{
			url:qxgl.paserUrl('user/queryUserform'),
			success:function(list){
				var data=JSON.parse(list);
				$("#usrManager").datagrid("loadData",data);
			}
		});
	});
	$('#doCreate').click(function(){
		showMessageDialog(qxgl.paserUrl('user/create'),'新建',500,500,true);
	});
	
	$('#doClear').click(function(){
		$('#queryForm').form('clear');
	});
	//url：窗口调用地址，title：窗口标题，width：宽度，height：高度，shadow：是否显示背景阴影罩层  
	function showMessageDialog(url, title, width, height, shadow) {  
	    var content = '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="no"></iframe>';  
	    var boarddiv = '<div id="msgwindow" title="' + title + '"></div>'//style="overflow:hidden;"可以去掉滚动条  
	    $(document.body).append(boarddiv);  
	    var win = $('#msgwindow').dialog({  
	        content: content,  
	        width: width,  
	        height: height,  
	        modal: shadow,  
	        title: title,  
	        onClose: function () {  
	            $(this).dialog('destroy');//后面可以关闭后的事件  
	        }  
	    });  
	    win.dialog('open');  
	}
});